package org.yypm.m_1_0;

import java.sql.*;

/**
 * @author 云烟飘渺o
 * @version 1.0
 * @description 借巨人之力，加速你的成长之路
 */
public class JdbcTest {

    /**
     * 1. 加载数据库驱动
     * 2. 建立连接
     * 3. 执行SQL
     * 4. 处理结构集
     * 5. 关闭资源
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String url = "jdbc:mysql://localhost:3306/mybatis";
        String username = "root";
        String password = "123456";

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(url, username, password);

            statement = connection.createStatement();

            String sql = "select * from user";

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                System.out.println("username:" + resultSet.getString("username"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(resultSet);
            close(statement);
            close(connection);
        }
    }


    private static void close(AutoCloseable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }

}
